package admin

import (
	"backend_api/configs"
	"backend_api/internal/middleware"
	"github.com/gin-gonic/gin"
	"net/http"
)

type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "无效的请求参数",
		})
		return
	}

	// 验证管理员账号密码
	if req.Username != configs.GetConfig().Admin.Username ||
		req.Password != configs.GetConfig().Admin.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 401,
			"msg":  "用户名或密码错误",
		})
		return
	}

	// 生成 JWT token
	token, err := middleware.GenerateAdminToken(req.Username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "生成令牌失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": gin.H{
			"token":    token,
			"username": req.Username,
		},
	})
}
